package com.yeshine.opendata.service.impl;

import com.yeshine.opendata.core.ServiceBase;
import com.yeshine.opendata.dao.ISysModelDao;
import com.yeshine.opendata.entity.SysModel;
import com.yeshine.opendata.service.ISysModelService;
import com.yeshine.opendata.utils.PageResult;
import com.yeshine.opendata.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by taohj on 2014/8/14.
 */
@Service
public class SysModelImpl extends ServiceBase<SysModel> implements ISysModelService {


    @Autowired
    private ISysModelDao dao;

    @Override
    public Result<SysModel> create(SysModel SysModel) {
        return new Result<SysModel>(dao.insert(SysModel)>0);
    }

    @Override
    public Result<SysModel> remove(SysModel SysModel) {
        return new Result<SysModel>(dao.delete(SysModel)>0);
    }

    @Override
    public Result<SysModel> modify(SysModel SysModel) {
        return new Result<SysModel>(dao.update(SysModel)>0);
    }

    @Override
    public Result<SysModel> getById(Integer id) {
        return new Result<SysModel>(dao.selectById(id));
    }

    @Override
    public Result<SysModel> getList(SysModel SysModel) {
        return new Result<SysModel>(dao.selectList(SysModel));
    }

    @Override
    public Result<SysModel> getByPage(PageResult<SysModel> pageResult) {
        pageResult.setRows(dao.selectbyPage(pageResult));
        return new Result<SysModel>(pageResult);
    }




    @Override
    public List<SysModel> getFunctionMenuTree(){
        List<SysModel> allList=this.getList(null).getList();
        List<SysModel> roots=getTreeModel(allList);
        return roots;
    }



    public List<SysModel> getTreeModel(List<SysModel> allModels){
        List<SysModel> rootModels = new ArrayList<SysModel>();
        for (int i = 0; i < allModels.size(); i++) {
            if (allModels.get(i).getParent() == null || allModels.get(i).getParent().getId()==null) {
                if (!rootModels.contains(allModels.get(i))) {
                    rootModels.add(allModels.get(i));
                }
                getTreeChidren(allModels, allModels.get(i));
            }
        }
        return rootModels;

    }



    public SysModel getTreeChidren(List<SysModel> models, SysModel model) {

        model.setChildren(model.getChildren() == null ? new ArrayList<SysModel>() : model.getChildren());
        for (int i = 0; i < models.size(); i++) {

            SysModel m = models.get(i);
            if (m.getParent() != null && model.getId().equals(m.getParent().getId())) {
                if (!model.getChildren().contains(m)) {
                    model.getChildren().add(m);
                }
                getTreeChidren(models, m);
            }
        }

        return model;
    }
}
